# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: site-packages\sqlalchemy\dialects\mysql\pyodbc.py
"""


.. dialect:: mysql+pyodbc
    :name: PyODBC
    :dbapi: pyodbc
    :connectstring: mysql+pyodbc://<username>:<password>@<dsnname>
    :url: http://pypi.python.org/pypi/pyodbc/

    .. note:: The PyODBC for MySQL dialect is not well supported, and
       is subject to unresolved character encoding issues
       which exist within the current ODBC drivers available.
       (see http://code.google.com/p/pyodbc/issues/detail?id=25).
       Other dialects for MySQL are recommended.

"""
from .base import MySQLDialect, MySQLExecutionContext
from ...connectors.pyodbc import PyODBCConnector
from ... import util
import re


class MySQLExecutionContext_pyodbc(MySQLExecutionContext):
    def get_lastrowid(self):
        cursor = self.create_cursor()
        cursor.execute("SELECT LAST_INSERT_ID()")
        lastrowid = cursor.fetchone()[0]
        cursor.close()
        return lastrowid


class MySQLDialect_pyodbc(PyODBCConnector, MySQLDialect):
    supports_unicode_statements = False
    execution_ctx_cls = MySQLExecutionContext_pyodbc
    pyodbc_driver_name = "MySQL"

    def __init__(self, **kw):
        kw.setdefault("convert_unicode", True)
        super(MySQLDialect_pyodbc, self).__init__(**kw)

    def _detect_charset(self, connection):
        """Sniff out the character set in use for connection results."""
        rs = connection.execute("SHOW VARIABLES LIKE 'character_set%%'")
        opts = {row[0]: row[1] for row in self._compat_fetchall(rs)}
        for key in ("character_set_connection", "character_set"):
            if opts.get(key, None):
                return opts[key]

        util.warn("Could not detect the connection character set.  Assuming latin1.")
        return "latin1"

    def _extract_error_code(self, exception):
        m = re.compile("\\((\\d+)\\)").search(str(exception.args))
        c = m.group(1)
        if c:
            return int(c)
        else:
            return


dialect = MySQLDialect_pyodbc
